//
//  WebViewController.m
//  GiftSay
//
//  Created by QQn1993 on 16/1/8.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "WebViewController.h"
#import "TFHpple.h"
#import "UMSocial.h"

#import "DataBaseHandle.h"

@interface WebViewController ()<UIWebViewDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) Loading *loading;
@property (nonatomic,strong) UIWebView *web;

@property (nonatomic,assign) CGFloat webHeight;

@property (nonatomic,copy) NSString *webstr;

@property (nonatomic,strong) UITableView *table;
@property (nonatomic,copy) NSString *cover_image_url;
@property (nonatomic,copy) NSString *name;

@property (nonatomic,strong)UIButton *insert;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.nameFromTactik > 0) {
        self.title = @"攻略详情";
//        NSLog(@"%@", self.url);
    } else {
        self.title = @"礼物详情";
    }
    
    
    self.webHeight = CGFLOAT_MIN;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    

    self.loading = [[Loading alloc] initWithFrame:CGRectMake(kWidth / 5 * 2, (kHeight - kWidth / 5)/3, kWidth / 5, kWidth / 5)];
    [self.loading start];
    
    self.web = [[UIWebView alloc] initWithFrame:CGRectZero];
    self.web.scrollView.delegate = self;
    self.web.delegate = self;
    
    [self createTableview];
    
    if ([self.type isEqualToString:@"post"]) {
        [self makeUpDatosource];
    }
    
    else{
        [self getWebViewWithUrl];
    }
    
    // Do any additional setup after loading the view.
}

- (void)createTableview
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStyleGrouped];
    self.table.dataSource = self;
    self.table.delegate = self;
    
    [self.view addSubview:self.table];
    [self.view addSubview:self.loading];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self.type isEqualToString:@"post"]) {
        return kHeight / 3;
    }
    else{

        return CGFLOAT_MIN;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([self.type isEqualToString:@"post"]) {
        return CGFLOAT_MIN;
    }
    else if(self.webHeight > 10.0){
        return kHeight / 15;
    }
    else{
        return CGFLOAT_MIN;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.webHeight > 10.0) {
        [self.loading stop];
        self.loading.hidden = YES;
    }
    
    return self.webHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([self.type isEqualToString:@"post"]) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight / 3)];
        [img setImageWithURL:[NSURL URLWithString:self.cover_image_url] options:YYWebImageOptionProgressiveBlur];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, img.frame.size.height / 4 * 3, kWidth, img.frame.size.height / 4)];
        label.text = [NSString stringWithFormat:@" %@",self.name];
        NSLog(@"%@",label.text);
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:25];
        [img addSubview:label];
        
        return img;

    }
    else{
        return nil;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ([self.type isEqualToString:@"post"]) {
        return nil;
    }
    else{
        return self.insert;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    NSLog(@"***************************");
    [cell.contentView addSubview:self.web];
    return cell;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGRect frame = self.web.frame;
    frame.size.width = kWidth;
    frame.size.height = 1;
    //    wb.scrollView.scrollEnabled = NO;
    self.web.frame = frame;
    
    self.webHeight = self.web.scrollView.contentSize.height;
    
    self.web.scrollView.scrollEnabled = NO;
    
    self.web.frame = CGRectMake(0, 0, kWidth, self.webHeight);
    
    [self.table reloadData];
}

//直接加载webview
- (void)getWebViewWithUrl
{
    [LYKNetWorkTool getWithUrl:self.url parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        
        NSString *str = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
        
        TFHpple *xpath = [[TFHpple alloc]initWithHTMLData:result];
        NSArray *dataArray = [xpath searchWithXPathQuery:@"//div"];
        for (TFHppleElement *httpE in dataArray) {
            
//            NSLog(@"**************** %@",httpE.raw);
            
            if ([httpE.attributes [@"class"] isEqualToString:@"wrapper download-banner"]) {
                str = [str stringByReplacingOccurrencesOfString:httpE.raw withString:@""];
                
            }
            
            else if ([httpE.attributes [@"class"] isEqualToString:@"cover"]){
                NSLog(@"%@",httpE.raw);
                
                NSArray *arrar = [NSArray arrayWithArray:[httpE.raw componentsSeparatedByString:@"\""]];
                self.cover_image_url = arrar[3];
            }
            
            else if ([httpE.attributes [@"class"] isEqualToString:@"td"]){
                TFHpple *hxpath = [[TFHpple alloc] initWithData:[httpE.raw dataUsingEncoding:NSUTF8StringEncoding] isXML:YES];
                NSArray *dataArray = [hxpath searchWithXPathQuery:@"//h1"];

                for (TFHppleElement *hhhh in dataArray) {
                    if ([hhhh.attributes [@"class"] isEqualToString:@"title"]) {
                        self.name = [self handleStringWithString:hhhh.raw];
                    }
                }
                
            }
            
        }
        
        self.webstr = str;
        
        [self.web loadHTMLString:str baseURL:[NSURL URLWithString:self.url]];
        
        [self.table reloadData];
        
    } fail:^(NSError *error) {
        
    }];
}

//截取字符串
-(NSString *)handleStringWithString:(NSString *)str{
    
    NSMutableString * muStr = [NSMutableString stringWithString:str];
    while (1) {
        NSRange range = [muStr rangeOfString:@"<"];
                         NSRange range1 = [muStr rangeOfString:@">"];
                         if (range.location != NSNotFound) {
            NSInteger loc = range.location;
            NSInteger len = range1.location - range.location;
            [muStr deleteCharactersInRange:NSMakeRange(loc, len + 1)];
        }else{
            break;
        }
    }
    return muStr;
}

//先处理数据，再加webview
- (void)makeUpDatosource
{
    [LYKNetWorkTool getWithUrl:self.url parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
        
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];

        NSDictionary *data = any[@"data"];
        NSLog(@"%@",data);
        NSLog(@"%@",data[@"title"]);
        self.name = data[@"title"];
        NSLog(@"%@",data[@"cover_image_url"]);
        self.cover_image_url = data[@"cover_image_url"];
        
        NSString *str = data[@"content_html"];
        
        self.webstr = str;
        
        [self.web loadHTMLString:str baseURL:[NSURL URLWithString:self.url]];
        
        [self.table reloadData];
        
    } fail:^(NSError *error) {
        
    }];

}

- (void)inserter
{
    NSLog(@"收藏");
    self.insert.selected = !self.insert.selected;
    if (self.insert.selected == YES) {
        self.insert.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
        [self.insert setTitle:@"取消收藏" forState:UIControlStateNormal];
        if (self.type == nil) {
            [[DataBaseHandle shareDataBase] insertMealsID:self.url AndName:self.name AndType:@"item" AndImg:self.cover_image_url];
        }
        else{
           [[DataBaseHandle shareDataBase] insertMealsID:self.url AndName:self.name AndType:self.type AndImg:self.cover_image_url];
        }
    }
    else if (self.insert.selected == NO){
        [self.insert setTitle:@"添加收藏" forState:UIControlStateNormal];
        self.insert.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
        
        [[DataBaseHandle shareDataBase] deleteMealsWhereID:self.url];
    }
}

- (void)delete
{
    NSLog(@"删除");
    self.insert.selected = !self.insert.selected;
    if (self.insert.selected == NO) {
        self.insert.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
        [self.insert setTitle:@"取消收藏" forState:UIControlStateNormal];
        [[DataBaseHandle shareDataBase] insertMealsID:self.url AndName:self.name AndType:self.type AndImg:@""];
    }
    else if (self.insert.selected == YES){
        [self.insert setTitle:@"添加收藏" forState:UIControlStateNormal];
        self.insert.backgroundColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
        
        [[DataBaseHandle shareDataBase] deleteMealsWhereID:self.url];
    }

}


//社会化分享
- (void)share
{
    NSLog(@"分享");
    //email  崩 transitionViewForCurrentTransition is not set, presentation controller was dismissed during the presentation? (<_UIFullscreenPresentationController: 0x7ffa7975dc70>)
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:nil shareText:@"网络创意新品~尽在礼物说！" shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, UMShareToRenren, UMShareToTencent, UMShareToDouban, UMShareToQQ, nil] delegate:self];
    
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    self.navigationController.tabBarController.tabBar.hidden = YES;
    [[DataBaseHandle shareDataBase] openDataBase];
    [[DataBaseHandle shareDataBase] createMealsTable];
    
    NSString *str = [[DataBaseHandle shareDataBase] selectMealsDressWhereId:self.url];
    
    if (str.length == 0 || [str isEqual:nil]) {
        self.insert = [UIButton buttonWithType:UIButtonTypeCustom];
        self.insert.frame = CGRectMake(kWidth / 6, self.webHeight + kHeight / 5, kWidth / 3 * 2, kHeight / 15);
        
        self.insert.backgroundColor = [UIColor colorWithRed:1 green:0.5 blue:0.5 alpha:1];
        self.insert.layer.masksToBounds = YES;
        self.insert.layer.cornerRadius = kHeight / 30;
        
        [self.insert addTarget:self action:@selector(inserter) forControlEvents:UIControlEventTouchUpInside];
        
        [self.insert setTitle:@"添加到收藏" forState:UIControlStateNormal];
    }
    
    else{
        self.insert = [UIButton buttonWithType:UIButtonTypeCustom];
        self.insert.frame = CGRectMake(kWidth / 6, self.webHeight + kHeight / 5, kWidth / 3 * 2, kHeight / 15);
        
        self.insert.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
        self.insert.layer.masksToBounds = YES;
        self.insert.layer.cornerRadius = kHeight / 30;
        
        [self.insert addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
        
        [self.insert setTitle:@"取消收藏" forState:UIControlStateNormal];
    }

}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.tabBarController.tabBar.hidden = NO;
    [[DataBaseHandle shareDataBase] closeDatabase];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
